<?php
/**
 * 首页
 * @return
 * @author yuncran@126.com
 */

namespace app\api\controller;

use app\BaseController;
use app\FieldKey;
use app\model\BannerModel;
use app\model\ConfigModel;
use app\model\RechargeModel;
use app\model\UserModel;
use PayPal\Api\Payment;
use think\Exception;
use think\facade\Log;

class Home extends BaseController
{

    /**
     * 获取联系人列表
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @author yuncran@126.com
     */
    public function getContacts()
    {
        $keyword = $this->request->param('keyword');
        try {
            $data = UserModel::getUserList([['status', '=', 'normal'], ['id', '<>', $this->uid]], $this->uid, FieldKey::user_field, $keyword);
        } catch (\Throwable $throwable) {
            return $this->renderError(lang('操作失败'));
        }
        return $this->renderSuccess($data);
    }

    /**轮播图
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author yuncran@126.com
     */
    public function getBanner()
    {
        $param = $this->request->param(['type' => 1]);
        $list = BannerModel::where(['status' => 1, 'type' => $param['type']])->cache('Banner-' . $param['type'], 60)
            ->withoutField(['url', 'type', 'update_time', 'describe', 'content'])->select();
        return $this->renderSuccess($list, lang('查询成功'));
    }


    public function callUrl()
    {
        $param = $this->request->get();
 
        return $this->renderSuccess($param, lang('查询成功'));
//        $recharge = Db::name('recharge')->where('order_sn', $param['orderid'])->find();
//        if ($recharge) {
//            if ($param['status'] == 'Y') {
//                Db::name('recharge')->where('order_sn', $param['orderid'])->update([
//                    'status' => 1,
//                    'update_time' => date('Y-m-d H:i:s', time()),
//                ]);
//            }
//        }
    }

    //失败操作
    public function callBack()
    {
        $param = $this->request->get();
        if (!empty($param)) {
            if ($param['status'] == 'Y') {
                $recharge = RechargeModel::where('order_sn', $param['orderid'])->find();
                if ($recharge) {
                    try {
                        RechargeModel::where('order_sn', $param['orderid'])->save([
                            'status' => $param['status'] == 'Y' ? 1 : 2,
                            'examine_status' =>  $param['status'] == 'Y' ? 1 : 2,
                            'update_time' => date('Y-m-d H:i:s', time()),
                        ]);
                    } catch (Exception $e) {
                        Log::info('查看', ['ooo' => $e->getMessage()]);
                    }

                    $user = UserModel::getUserInfoFind(['id' => $recharge['user_id']], 'id,money,render');
                    UserModel::addUserInc($recharge['user_id'], 'money', $recharge['gold_money']);
                    event('UserMoney', ['user_id' => $user['id'], 'money' => $recharge['gold_money'], 'before' => $user['render'],
                        'after' => bcadd($user['money'], $recharge['gold_money'], 2), 'type' => 4,
                    ]);

                    //充值消耗拿提成
                    event('DrawLog', [
                        'merchant_id' => $recharge['merchant_id'],
                        'user_id' => $recharge['merchant_id'],
                        'money' => $recharge['gold_money'],
                        'type' => 1,
                        'expend' => 'recharge',
                    ]);

                    $url = url('index/Index/pay_success');
                    // 重定向用户
                    return redirect($url);
                }
            } elseif ($param['status'] == 'N') {
                RechargeModel::where('order_sn', $param['orderid'])->save([
                    'status' => $param['status'] == 'Y' ? 1 : 2,
                    'examine_status' =>  $param['status'] == 'Y' ? 1 : 2,
                    'update_time' => date('Y-m-d H:i:s', time()),
                ]);
                
                $url = url('index/Index/pay_fail');
                // 重定向用户
                return redirect($url);
            }
        }
    }

    private $account = '15518337505';
    

    public function payPalCallback5()
    {
        $logs = "notice \r" . date("Y-m-d H:i:s", time()) . "\r\n" . json_encode($_GET);
        file_put_contents('data_log.txt', $logs, FILE_APPEND);
        if ($_GET['success'] == true) {
            try {
                $recharge = RechargeModel::where('order_sn', $_GET['orderid'])->find();
                RechargeModel::where('order_sn', $_GET['orderid'])->save([
                    'status' => 1,
                    'examine_status' => 1,
                    'update_time' => date('Y-m-d H:i:s', time()),
                ]);
                $user = UserModel::getUserInfoFind(['id' => $recharge['user_id']], 'id,money,render');
                UserModel::addUserInc($recharge['user_id'], 'money', $recharge['gold_money']);
                event('UserMoney', ['user_id' => $user['id'], 'money' => $recharge['gold_money'], 'before' => $user['render'],
                    'after' => bcadd($user['money'], $recharge['gold_money'], 2), 'type' => 4,
                ]);
                //充值消耗拿提成
                event('DrawLog', [
                    'merchant_id' => $recharge['merchant_id'],
                    'user_id' => $recharge['merchant_id'],
                    'money' => $recharge['gold_money'],
                    'type' => 1,
                    'expend' => 'recharge',
                ]);
                $url = url('index/Index/pay_success');
                // 重定向用户
                return redirect($url);
            } catch (Exception $e) {
                file_put_contents('data_log.txt', json_encode($e->getMessage()), FILE_APPEND);
            }
        }else{
            RechargeModel::where('order_sn', $_GET['orderid'])->save([
                'status' => 2,
                'examine_status' => 2,
                'update_time' => date('Y-m-d H:i:s', time()),
            ]);
            $url = url('index/Index/pay_fail');
            // 重定向用户
            return redirect($url);
        }
    }


    public function payPalCallback22()
    {
        // 设置PayPal API凭证
        $clientId = ConfigModel::where('name', 'example_paypal_key')->cache(true, 60)->value('value');
        $clientSecret = ConfigModel::where('name', 'example_paypal_secret')->cache(true, 60)->value('value');


        $logs = PHP_EOL . "success" . PHP_EOL . date("Y-m-d H:i:s", time()) . PHP_EOL . json_encode($_GET);
        file_put_contents('data_log.txt', $logs, FILE_APPEND);



        if (isset($_GET['paymentId']) && isset($_GET['token']) && isset($_GET['PayerID'])) {
            $paymentId = $_GET['paymentId'];
            $payerId = $_GET['PayerID'];
            try {
                // $apiContext = new \PayPal\Rest\ApiContext(
                //     new \PayPal\Auth\OAuthTokenCredential($clientId, $clientSecret)
                // );

                // $payment = \PayPal\Api\Payment::get($paymentId, $apiContext);
          

                
                // $execution = new \PayPal\Api\PaymentExecution();
                // $execution->setPayerId($payerId);
                
                $recharge = RechargeModel::where('order_sn', (int)$_GET['orderid'])->find();
                $logs2 = PHP_EOL . "order" . PHP_EOL . date("Y-m-d H:i:s", time()) . PHP_EOL . json_encode($recharge);
                file_put_contents('data_log.txt', $logs2, FILE_APPEND);                

                // $result = $payment->execute($execution, $apiContext);
              
                // $logs3 = PHP_EOL . "result" . PHP_EOL . date("Y-m-d H:i:s", time()) . PHP_EOL . json_encode($result);
                // file_put_contents('data_log.txt', $logs3, FILE_APPEND);   
                
                echo "支付成功！交易ID: " .$payerId ;
            } catch (Exception $ex) {

                echo "支付执行失败： " . $ex->getMessage();
            }
        } else {
            
            $url = url('index/Index/index');
            // 重定向用户
            return redirect($url);
            echo "支付失败或未提供必要参数。";
        }

    }



 
    public function payOrderId()
    {
        $order_id = input('order_id');
        $recharge = RechargeModel::where('order_sn', $order_id)->find();
        if(isset($recharge)) {
            if ($recharge['status'] == 1 || $recharge['examine_status'] == 1) {
                return json(['code'=>200,'msg'=>'该订单已支付','data'=>'']);
            }
        }
    }

    public function payPalCallback33()
    {
        $url = url('index/Index/pay_success?order_id=' . $_GET['order_id']);
        // 重定向用户
        return redirect($url);
    }


    public function callback_url()
    {
        $param = input();
        $logs = "notice \r" . date("Y-m-d H:i:s", time()) . "\r\n" . json_encode(input());
        file_put_contents('data_log.txt', $logs, FILE_APPEND);
        if(!empty($param)){
                if ($param['pay_status'] == 'success') {
                    $recharge = RechargeModel::where('order_sn', $param['order_id'])->find();
                 
                    if($recharge['status'] == 1 || $recharge['examine_status'] == 1){
                        echo('success');die;
                    }
                    
                    RechargeModel::where('order_sn', $param['order_id'])->save([
                        'status' => 1,
                        'examine_status' => 1,
                        'update_time' => date('Y-m-d H:i:s', time()),
                    ]);
                    $user = UserModel::getUserInfoFind(['id' => $recharge['user_id']], 'id,money,render');
                    UserModel::addUserInc($recharge['user_id'], 'money', $recharge['gold_money']);
                    event('UserMoney', ['user_id' => $user['id'], 'money' => $recharge['gold_money'], 'before' => $user['render'],
                        'after' => bcadd($user['money'], $recharge['gold_money'], 2), 'type' => 4,
                    ]);
                    //充值消耗拿提成
                    event('DrawLog', [
                        'merchant_id' => $recharge['merchant_id'],
                        'user_id' => $recharge['merchant_id'],
                        'money' => $recharge['gold_money'],
                        'type' => 1,
                        'expend' => 'recharge',
                    ]);
                    echo('success');die;
                } 
        }
        echo('success');
    }
    
    
    /**正式在使用 */
    public function payPalCallback()
    {
        // 设置PayPal API凭证
        $clientId = ConfigModel::where('name', 'example_paypal_key')->cache(true, 60)->value('value');
        $clientSecret = ConfigModel::where('name', 'example_paypal_secret')->cache(true, 60)->value('value');

//        $clientId = 'AahK573eG2zp1L_-rfNlnGSzqF_giayL4suHg878tbDwSOS9N4UKAOKWCHtiRiK5gLRK1op0sOkqM_aJ';
//        $clientSecret = 'ENm6Ty0GRz-U2DRHAVR6PkLUjryEIj_ni5zGpU2fsjUWPZXgBYh7toCOuZVUoteqiQ5yE2V-iKV_l3Jr';

        $logs = PHP_EOL . "success" . PHP_EOL . date("Y-m-d H:i:s", time()) . PHP_EOL . json_encode($_GET);
        file_put_contents('data_log.txt', $logs, FILE_APPEND);
        if (isset($_GET['paymentId']) && isset($_GET['token']) && isset($_GET['PayerID'])) {
            $paymentId = $_GET['paymentId'];
            $payerId = $_GET['PayerID'];
            try {
                $execution = new \PayPal\Api\PaymentExecution();
                $execution->setPayerId($payerId);
                $apiContext = new \PayPal\Rest\ApiContext(
                    new \PayPal\Auth\OAuthTokenCredential($clientId, $clientSecret)
                );

                $apiContext->setConfig(
                    array(
                        'mode' => 'live', // live,sandbox
                        'http.ConnectionTimeOut' => 30,
                    )
                );
                $payment = Payment::get($paymentId, $apiContext);
                $result = $payment->execute($execution, $apiContext);

                $logs1 = PHP_EOL . "success" . PHP_EOL . date("Y-m-d H:i:s", time()) . PHP_EOL . json_encode($payment);
                file_put_contents('data_log.txt', $logs1, FILE_APPEND);                
                
                // print_r($payment);
                
                // halt($result);

                $recharge = RechargeModel::where('order_sn', $_GET['orderid'])->find();

                RechargeModel::where('order_sn', $_GET['orderid'])->save([
                    'status' => 1,
                    'examine_status' => 1,
                    'update_time' => date('Y-m-d H:i:s', time()),
                ]);

                $user = UserModel::getUserInfoFind(['id' => $recharge['user_id']], 'id,money,render');
                UserModel::addUserInc($recharge['user_id'], 'money', $recharge['gold_money']);
                event('UserMoney', ['user_id' => $user['id'], 'money' => $recharge['gold_money'], 'before' => $user['render'],
                    'after' => bcadd($user['money'], $recharge['gold_money'], 2), 'type' => 4,
                ]);
                //充值消耗拿提成
                event('DrawLog', [
                    'merchant_id' => $recharge['merchant_id'],
                    'user_id' => $recharge['merchant_id'],
                    'money' => $recharge['gold_money'],
                    'type' => 1,
                    'expend' => 'recharge',
                ]);

            } catch (Exception $ex) {

                RechargeModel::where('order_sn', $_GET['orderid'])->save([
                    'status' => 2,
                    'examine_status' => 2,
                    'update_time' => date('Y-m-d H:i:s', time()),
                ]);
            }
        } else {
            echo "支付失败或未提供必要参数。";
            $url = url('index/Index/pay_fail');
            // 重定向用户
            return redirect($url);
        }

    }
    

}